package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.HwOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/admin/common")
public class CommonController {

    @Autowired
    private HwOssUtil hwOssUtil;

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        // 检查文件是否为空
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要上传的文件");
        }

        // 检查文件大小（限制为100MB）
        long maxSize = 100 * 1024 * 1024; // 100MB in bytes
        if (file.getSize() > maxSize) {
            return Result.error("文件大小超过限制（最大100MB）");
        }
        try {
            // 设置默认的文件保存路径，使用课题编号作为子目录
            String uploadDir = "review/sky/";

            // 获取原始文件名和扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            String objectName = UUID.randomUUID().toString() + extension;

            // 使用原始文件名上传
            //String fileUrl = hwOssUtil.uploadFileWithName(file, uploadDir, file.getOriginalFilename());
            //使用自定义文件名上传
            String fileUrl = hwOssUtil.uploadFileWithName(file, uploadDir, objectName);
            log.info("文件上传成功，文件URL：{}", fileUrl);

            //预签名URL
            String presignedUrl = hwOssUtil.generatePresignedUrl(fileUrl, 3600, true);
            log.info("文件上传成功，文件URL：{}", presignedUrl);
            return Result.success(presignedUrl);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return Result.error(MessageConstant.UPLOAD_FAILED + e.getMessage());
        }
    }
}
